package ${domain}.action.ajax.wsys;

import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import ${domain}.frame.auth.LocalData;
import ${domain}.frame.base.BaseResponse;
import ${domain}.frame.base.ErrorType;
import ${domain}.frame.excel.WExcel;
import ${domain}.frame.excel.exception.TemplateNotMatchException;
import ${domain}.frame.utils.LogUtil;
import ${domain}.frame.utils.MapperUtil;
import ${domain}.frame.utils.ResponseUtil;
import ${domain}.frame.utils.ValidationUtil;
import ${domain}.module.wsys.ent.File;
import ${domain}.module.wsys.mgr.FileManager;
import ${domain}.module.wsys.req.FileCreateRequest;
import ${domain}.module.wsys.req.FileDeleteRequest;
import ${domain}.module.wsys.req.FileFindRequest;
import ${domain}.module.wsys.rsp.FileCreateResponse;
import ${domain}.module.wsys.rsp.FileDeleteResponse;
import ${domain}.module.wsys.rsp.FileFindResponse;
import ${domain}.module.wsys.rsp.FileUploadResponse;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

public class FileAjax {

    @Autowired
    private FileManager fileManager;

    public FileCreateResponse create(FileCreateRequest request) {
        return fileManager.create(request, LocalData.getToken());
    }

    public FileDeleteResponse delete(FileDeleteRequest request) {
        return fileManager.delete(request, LocalData.getToken());
    }

    public FileFindResponse find(FileFindRequest request) {
        return fileManager.find(request, LocalData.getToken());
    }

    public Object template() {
        return ResponseUtil.apply(new WExcel<>(File.class));
    }

    public Object exports(FileFindRequest request) {
        FileFindResponse response = fileManager.find(request, LocalData.getToken());
        if (response.hasError()) {
            return response;
        } else if (response.getTotalCount() == 0) {
            response.addError(ErrorType.BUSINESS_ERROR, "导出数据为空");
            return response;
        }
        return ResponseUtil.apply(new WExcel<>(File.class).addDatas(response.getResult()));
    }

    public Object imports(MultipartFile file) {
        BaseResponse baseResponse = new BaseResponse();
        try {
            // 检查文件格式
            String originalFilename = file.getOriginalFilename() != null ? file.getOriginalFilename() : "";
            if (originalFilename.matches("\\.xlsx?")) {
                baseResponse.addError(ErrorType.BUSINESS_ERROR, "上传文件格式错误！");
                return baseResponse;
            }
            // 兼容2003以前老版本.xls
            ExcelTypeEnum excelTypeEnum = file.getOriginalFilename().endsWith(".xlsx") ? ExcelTypeEnum.XLSX : ExcelTypeEnum.XLS;
            WExcel sheet = new WExcel<>(File.class).read(file.getBytes(), excelTypeEnum, new WExcel.Processor<File>() {
                @Override
                public List<String> exec(File o, int index) {
                    FileCreateRequest request = MapperUtil.map(o, FileCreateRequest.class);
                    return ValidationUtil.validate(request);
                }
            });

            if (sheet.hasError()) {
                return ResponseUtil.apply(sheet.getBytes(), sheet.getName() + "-检查.xlsx");
            } else {
                return baseResponse;
            }
        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.dumpException(e);
            baseResponse.addError(ErrorType.BUSINESS_ERROR, "上传文件出错");
        } catch (TemplateNotMatchException e) {
            baseResponse.addError(ErrorType.BUSINESS_ERROR, e.getMessage());
        }
        return baseResponse;
    }

    public FileUploadResponse upload(MultipartFile file) {
        FileUploadResponse fileUploadResponse = new FileUploadResponse();
        String fileName = file.getOriginalFilename();

        //========
        // todo 处理文件
        //========
        fileUploadResponse.setId(1L);
        fileUploadResponse.setUrl("example.com\\img\\1.jpg");
        fileUploadResponse.setUrlDownload("example.com\\img\\1.jpg");

        if (file != null) {
            fileUploadResponse.addError(ErrorType.BUSINESS_ERROR, "文件上传成功,但未处理文件[" + fileName + "]!");
        } else {
            fileUploadResponse.addError(ErrorType.BUSINESS_ERROR, "文件上传失败!");
        }

        return fileUploadResponse;
    }

    public Object download() {
        try {
            //========
            // todo 下载示例
            //========
            byte[] bytes = "test".getBytes();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", URLEncoder.encode("example.test", "utf-8"));
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            BaseResponse baseResponse = new BaseResponse();
            baseResponse.addError(ErrorType.BUSINESS_ERROR, "");
            return baseResponse;
        }
    }
}
